package com.je.thrid.importsource;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import javax.sql.DataSource;

import com.google.common.collect.Lists;
import com.je.core.util.bean.DynaBean;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;

/**
 * @program: je-platform
 * @author: LIULJ
 * @create: 2020-07-13 18:49
 * @description: 数据库导入源
 */
public class DataSourceImportSource extends AbstractDynaBeanImportSource {

    protected DataSource dataSource;

    protected String sql;

    protected String tableCode;

    protected List<Object> params;

    protected DataSourceImportSource() {}

    public DataSourceImportSource(DataSource dataSource, String sql, String tableCode) {
        this.dataSource = dataSource;
        this.sql = sql;
        this.tableCode = tableCode;
    }

    public DataSourceImportSource(DataSource dataSource, String sql, String tableCode, List<Object> params) {
        this.dataSource = dataSource;
        this.sql = sql;
        this.params = params;
        this.tableCode = tableCode;
    }

    @Override
    public List<DynaBean> read() throws SQLException {
        Object[] paramArray = null;
        if (params != null && !params.isEmpty()) {
            paramArray = params.toArray();
        }
        List<Entity> entities = Db.use(dataSource).query(sql, paramArray);
        List<DynaBean> result = Lists.newArrayList();
        entities.forEach(eachEntity -> {
            DynaBean eachBean = new DynaBean(tableCode, true);
            Set<String> fieldNames = eachEntity.getFieldNames();
            for (String fieldName : fieldNames) {
                eachBean.set(fieldName, eachEntity.get(fieldName));
            }
            result.add(eachBean);
        });
        return result;
    }

}
